#include "functions.h"

SDL_Surface *screen;
TTF_Font *font;
SDL_Surface *text_surface;
SDL_Color fcolor = {255,255,255};
const SDL_VideoInfo *dispinfo;

void Debug(const char *format, ...){
	char str[1024];
	char filename[1024];

	va_list argp;		
	va_start(argp, format);
	vsprintf(str, format, argp);
	va_end(argp);

	FILE *fDebug;
	sprintf(filename, "/dev_hdd0/game/%s/USRDIR/log.txt",hdd_folder_installed);
	fDebug = fopen(filename, "a+");

	fputs(str, fDebug);

	fclose(fDebug);
}

static void sys_callback(uint64_t status, uint64_t param, void* userdata) {
	switch (status) {
		case SYSUTIL_EXIT_GAME:
			exit(0);
			break;
	default:
		break;
	}
}

void InitSDL() {
	sysModuleLoad(SYSMODULE_FS);
	sysModuleLoad(SYSMODULE_IO);
	Debug("\n\nBienvenido a RNA: \n");
	SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO);
	TTF_Init();
	dispinfo = SDL_GetVideoInfo();
	screen = SDL_SetVideoMode(dispinfo->current_w, dispinfo->current_h,32,SDL_DOUBLEBUF);
	sysUtilRegisterCallback(SYSUTIL_EVENT_SLOT0, sys_callback, NULL);
	ioPadInit(7);
	atexit(SDL_Quit);
	SDL_ShowCursor(SDL_DISABLE);
	char filename[1024];
	sprintf(filename, "/dev_hdd0/game/%s/USRDIR/rna_font.ttf",hdd_folder_installed);
	font=TTF_OpenFont(filename, dispinfo->current_h/50);
	if (!font) exit(0);
	else Debug("FONT LOADED \n");
}
void free_surf(SDL_Surface* surf){
	if(surf) SDL_FreeSurface(surf);
}
void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip) {
    SDL_Rect offset;
    offset.x = x;
    offset.y = y;
    SDL_BlitSurface( source, clip, destination, &offset );
}
void fontWrite(int x, int y, const char* text) {
	if (text != NULL) {
		text_surface=TTF_RenderText_Solid(font, text, fcolor);
		apply_surface(x, y, text_surface, screen, NULL);
		free_surf(text_surface);
	} else {
		exit(0);
	}
}
void fontPrintf(int x, int y, const char *format, ...) {
    va_list opt;
    char buff[2048];
    va_start(opt, format);
    vsnprintf(buff, sizeof(buff), format, opt);
    va_end(opt);
	fontWrite(x, y, buff);
}

padData getPadData(int i) {
	padInfo padinfo;
	padData paddata;
	ioPadGetInfo(&padinfo);
	if(padinfo.status[i]){
		ioPadGetData(i, &paddata);
	}
	return paddata;
}
